import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';

import '../../../config/router_page_name.dart';
import '../../../services/auth_service.dart';

class LoginLogic extends GetxController {
  final AuthService _authService = AuthService();
  
  final usernameController = TextEditingController();
  final passwordController = TextEditingController();
  
  final isLoading = false.obs;
  
  @override
  void onClose() {
    usernameController.dispose();
    passwordController.dispose();
    super.onClose();
  }
  
  Future<void> login() async {
    if (usernameController.text.isEmpty || passwordController.text.isEmpty) {
      SmartDialog.showToast('用户名和密码不能为空');
      return;
    }
    
    isLoading.value = true;
    
    try {
      bool success = await _authService.login(
        usernameController.text.trim(),
        passwordController.text.trim(),
      );
      
      if (success) {
        Get.offAllNamed(RouterPageName.mainPage);
      } else {
        SmartDialog.showToast('用户名或密码错误');
      }
    } catch (e) {
      SmartDialog.showToast('登录失败: $e');
    } finally {
      isLoading.value = false;
    }
  }
  
  void goToRegister() {
    Get.toNamed(RouterPageName.registerPage);
  }
}
